<template>
	<view style="padding: 40rpx 20rpx">
		<scan></scan>
		<div style="margin-bottom: 20rpx;">
			<button type="primary" size="mini" v-if="bluetoothStatus == '未连接'" class="bluetooth" @tap="showBlueTooth">
				蓝牙秤:
				{{bluetoothStatus}}
			</button>
			<button type="primary" size="mini" v-else class="bluetooth" @tap="closeConnet()">
				蓝牙秤:
				{{bluetoothStatus}}
			</button>
		</div>
		<view class="search-view">
			<view class="search">
				<text @tap="scanCode()" style="font-size: 50rpx;margin-right: 20rpx;" class="tn-icon-scan"></text>
				<input v-model="waybill_no" style="font-size: 28rpx;width: 100%;" class="uni-input"
					confirm-type="search" placeholder="请输入或扫描运单号/集包号进行发运" />
			</view>
			<tn-button @tap="pickup" backgroundColor="tn-bg-blue" fontColor="#fff">确 定</tn-button>
		</view>
		<view class="weight">
			<view class="weight-name">
				包裹重量:
			</view>
			<view class="weight-input">
				<input disabled v-model="$store.state.weight" style="font-size: 28rpx;width: 100%;" class="uni-input"
					confirm-type="search" placeholder="包裹重量" />
			</view>
		</view>
		<view class="goods_type">
			<view class="list_content">
				<view class="" style="margin-right: 10rpx;">
					产品标识:
				</view>
				<view @tap="changeType(item)" :class="goods_type_id == item.id?'list_item list_active':'list_item'"
					v-for="(item,index) in typeList" :key="index">
					{{item.name}}
				</view>
			</view>

			<view class="list_content">
				<view class="" style="margin-right: 10rpx;">
					快递类型:
				</view>
				<view @tap="changeExpressType(item)" :class="expressType == item.id?'list_item list_active':'list_item'"
					v-for="(item,index) in expressList" :key="index">
					{{item.name}}
				</view>
			</view>
		</view>
		<view class="scan-content">
			<div class="scan-title">
				<span>扫描明细</span>
				<span>本次扫描数量: {{scanList.length}}</span>
			</div>
			<div style="text-align: center;padding: 40rpx 0;color: #999;" v-if="!scanList.length">
				暂无揽收记录
			</div>
			<div class="scan-list">
				<div v-for="(item,index) in scanList" :key="index" class="scan-item">
					<span> {{item.waybill_no}}</span>
					<span> 重量:{{item.weight}}kg</span>
					<span> {{item.goods_name}}</span>
					<span> {{item.express_name}}</span>
				</div>
			</div>
		</view>
		<view class="" style="display: flex;justify-content: center;margin-top: 100rpx;">
			<tn-button @tap="back" width="550rpx" height="80rpx" backgroundColor="tn-bg-blue"
				fontColor="tn-color-white">扫描完成</tn-button>
		</view>
		<tn-modal @tap='clickClose' v-model="showClose" title="提示" content="是否断开连接?" :button="button"></tn-modal>

		<view v-show="show" class="cu-dialog" @tap="show = false">
			<view class="dialog-content">
				<view class="cu-bar" style="margin-bottom: 20rpx;">
					<view class="content" style="color: #ecd2ac;">蓝牙设备</view>
					<tn-loading mode="circle" :show="true"></tn-loading>
				</view>
				<scroll-view scroll-y="true" class="v30">
					<view class="cu-list">
						<view @tap.stop="connect(item)" class="cu-item" v-for="(item,index) in list" :key="index">
							<view class="content" v-if="item.name">{{item.name}}<text
									style="color: black;font-weight: 700;margin-left: 20rpx;">{{item.address}}</text>
							</view>
							<view class="content" v-if="item.name ==' '">
								无名称
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script>
	import scan from "@/common/pdaScan.vue"
	const bluetooth = uni.requireNativePlugin('LY-BluetoothWeight');
	export default {
		components: {
			scan
		},
		data() {
			return {
				number: 0,
				data: {},
				scanList: [],
				waybill_no: "",
				bluetoothStatus: '未连接',
				list: [],
				show: false,
				showClose: false,
				button: [{
						text: '取消',
						backgroundColor: '#E6E6E6',
						fontColor: '#FFFFFF'
					},
					{
						text: '确定',
						backgroundColor: '#6f3e25',
						fontColor: '#FFFFFF'
					}
				],
				expressList: [{
					name: "标快",
					id: 1
				}, {
					name: "特快",
					id: 2
				}],
				goods_type_id: '',
				expressType: '',
				goods_name: '',
				express_name: '',
				typeList: [],
			}
		},
		onLoad(options) {
			console.log(options)
			this.getlistType()
			this.data = JSON.parse(options.data)
			this.list = JSON.parse(uni.getStorageSync('blueList'))
			this.$store.commit('setWeight', 0)
			bluetooth.initBluetooth({
				isPrimitive: false
			})
			if (uni.getStorageSync('deviceInfo')) {
				this.connect(JSON.parse(uni.getStorageSync('deviceInfo')))
			}
		},
		onUnload() {
			bluetooth.disconnectBluetooth();
			this.bluetoothStatus = '未连接'
			this.showClose = false
		},
		onShow: function() {
			var that = this
			uni.$off('scancodedate') // 每次进来先 移除全局自定义事件监听器  
			uni.$on('scancodedate', function(data) {
				that.waybill_no = data.code
				that.pickup()
			})
		},
		methods: {
			changeType(item) {
				this.goods_type_id = item.id
				this.goods_name = item.name
			},
			changeExpressType(item) {
				if (item.id == this.expressType) {
					this.expressType = ''
					this.express_name = ''
				} else {
					this.expressType = item.id
					this.express_name = item.name
				}
			},
			getlistType() {
				this.$api.admin({
					apiUrl: '/goods/listType',
					param: {}
				}).then((res) => {
					this.typeList = res.data.data.list
					this.goods_type_id = res.data.data.list[0].id
					this.goods_name = res.data.data.list[0].name
				}).catch((err) => {})
			},
			showBlueTooth() {
				uni.vibrateShort()
				bluetooth.discoveryBluetooth((res) => { //多次回调，可添加到数组展示蓝牙列表
					console.log(res)
					//res数据：{"status":5,"data":{"name":"蓝牙名称","address":"蓝牙地址"}}
					if (res.status == 5 && res.data.name) {
						this.list = this.list.concat(res.data)
						uni.setStorageSync('blueList', JSON.stringify(this.list));
					}
				});
				this.show = true
			},
			// 连接设备
			async connect(item) {
				let self = this;
				console.log(item)
				uni.vibrateShort()
				bluetooth.connectBlutoothWithName({
					blutoothName: item.name //蓝牙名称
				}, (res) => {
					switch (parseInt(res.status)) {
						case 0: {
							uni.showToast({
								title: '请先配对电子秤',
								icon: 'error'
							})
						}
						break;
						case 1: {
							self.$store.commit('setWeight', res.data)
							// this.weight = res.data;
						}
						break;
						case 2: {
							uni.showToast({
								title: '连接成功',
								icon: 'success'
							})
							uni.setStorageSync('deviceInfo', JSON.stringify(item));
							self.bluetoothStatus = item.name + ' ' + item.address
							self.show = false
						}
						break;
						case 3: {
							// uni.showToast({
							// 	title: '蓝牙已断开',
							// 	icon: 'error'
							// })
							self.bluetoothStatus = '未连接'
						}
						break;
						default:
							break;
					}
				})
			},
			//断开连接
			closeConnet() {
				uni.vibrateShort()
				this.showClose = true
			},
			clickClose(e) {
				uni.vibrateShort()
				if (e.index == 0) {
					this.showClose = false
				} else {
					// this.$store.commit('closeBluetoothAdapter')
					// this.$store.commit('openBluetoothAdapter')
					bluetooth.disconnectBluetooth();
					this.bluetoothStatus = '未连接'
					this.showClose = false
				}
			},
			scanCode() {
				var that = this
				// 允许从相机和相册扫码
				uni.scanCode({
					success: function(res) {
						console.log('条码类型：' + res.scanType);
						console.log('条码内容：' + res.result);
						that.waybill_no = res.result
						that.pickup()
					}
				});
			},
			cheackWeight() {
				var that = this
				return new Promise((resove, reject) => {
					var weight1 = ''
					var weight2 = ''
					weight1 = this.$store.state.weight
					var times = setTimeout(() => {
						weight2 = that.$store.state.weight
						if (weight1 == weight2) {
							clearTimeout(times);
							resove(true)
						} else {
							clearTimeout(times);
							resove(false)
						}
					}, 500)
				})
			},
			async pickup() {
				let isWeight = await this.cheackWeight()
				if (!isWeight) {
					this.$t.message.toast('重量未稳定请重试')
					return
				}
				uni.showLoading({
					title: '获取扫描信息中...',
					icon: 'none'
				});
				this.$api.admin({
					apiUrl: '/order/updateConsign',
					param: {
						"scan_number": this.waybill_no, //运单号
						"trade_code": this.data.trade_code,
						"goods_type_id": this.goods_type_id, //货物类型 ID
						"size": this.data.size, //大小件 （1-小件 2-大件）
						"delivery_method": this.data.delivery_method, //送货方式（1-上门取件 2-自送货物）
						"express_type": this.expressType, //快递产品类型（1-标快 2-特快）
						"weight_pickup": this.$store.state.weight
					}
				}).then((res) => {
					this.scanList.unshift({
						waybill_no: this.waybill_no,
						weight: this.$store.state.weight,
						goods_name: this.goods_name,
						express_name: this.express_name
					})
					uni.hideLoading();
				}).catch((err) => {
					uni.hideLoading();
				})
			},

			back() {
				uni.reLaunch({
					url: '/pages/index/home'
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.search-view {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.search {
		border: 1rpx solid #d9d9d9;
		border-radius: 10rpx;
		padding: 10rpx 20rpx;
		width: 80%;
		display: flex;
		align-items: center;
	}

	.scan-content {
		margin-top: 20rpx;

		.scan-title {
			background-color: #3D7EFF;
			padding: 20rpx;
			color: #fff;
			display: flex;
			justify-content: space-between;
		}

		.scan-list {
			margin-top: 30rpx;

			.scan-item {
				border-bottom: 1rpx solid #e7e7e7;
				padding: 30rpx 0;
				display: flex;
				justify-content: space-between;
			}
		}
	}

	.weight {
		border-radius: 10rpx;
		display: flex;
		margin-top: 20rpx;

		.weight-name {
			border: 1rpx solid #c7c7c7;
			padding: 10rpx;
			width: 25%;
			text-align: center;
		}

		.weight-input {
			border: 1rpx solid #dcdcdc;
			background-color: #dcdcdc;
			padding: 10rpx;
			width: 75%;
		}
	}

	.cu-bar {
		font-size: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.content {
			margin-right: 10rpx;
			position: relative;
			top: -3rpx;
		}
	}

	.v30 {
		height: 50vh;

		.cu-list {
			.cu-item {
				text-align: center;
				padding: 20rpx 0;
				border-bottom: 1rpx solid #ecd2ac;
				color: #666;
			}
		}

	}

	.cu-dialog {
		position: fixed;
		background-color: rgba(0, 0, 0, .3);
		width: 100%;
		height: 100vh;
		top: 0;
		left: 0;

		.dialog-content {
			background-color: #fff;
			position: absolute;
			bottom: 0;
			width: 100%;
			padding: 20rpx;
		}
	}

	.list_content {
		display: flex;
		flex-wrap: wrap;
		margin-top: 20rpx;
		align-items: center;

		.list_item {
			margin-right: 10rpx;
			font-size: 28rpx;
			border: 1rpx solid #d9d9d9;
			margin-bottom: 10rpx;
			padding: 2rpx 10rpx;
			border-radius: 10rpx;
			color: #666;
		}

		.list_active {
			background-color: #3D7EFF;
			border: 1rpx solid #3D7EFF;
			color: #fff;
		}
	}
</style>